<?php

require_once 'sys.inc';
require_once 'ajax.inc';

$functions = array(
	"get_score" => new SafeFunc("get_score", array("id1", "id2")),
	"get_search" => new SafeFunc("get_search", array("query")),
);

if (!run_function($functions))
	return;

/* ajax functions */
	
function get_score($arg)
{
    global $table_game;
	
	$id1 = 0+$arg->id1;
	$id2 = 0+$arg->id2;
	if ($id1 == 0 || $id2 == 0 || $id1 == $id2)
	{
	    echo "param error";
	    return;
	}
	$q = "SELECT * FROM $table_game
		WHERE black_id=$id1 AND white_id=$id2 OR black_id=$id2 AND white_id=$id1";
	$result = mysql_query($q);
	$score1 = 0;
	$score2 = 0;
	while ($row = mysql_fetch_object($result))
	{
		if ($row->bresult == 1)
		{
			if ($row->black_id == $id1)
				$score1++; 
			else 
				$score2++;
		}
		elseif ($row->bresult == 0)
		{
			if ($row->black_id == $id1)
				$score2++;
			else 
				$score1++;
		}
		else
		{
				$score1 += 0.5;
				$score2 += 0.5;
		}
	}
	echo "$score1 : $score2";
}

function get_search($arg)
{
    global $table_player;
	
    $query = strtoupper($arg->query);
	$where = "";
	if (preg_match("/^\d+$/", $query))
	{
		$where = "player_id=$query";
	}
	else
	{
		$where = "UPPER(surname) LIKE '%" . $query . "%'
		ORDER BY surname, name 
		LIMIT 10";
	}
	$q = "SELECT player_id, name, surname 
		FROM $table_player 
		WHERE $where";
	$result = mysql_query($q);
	$resp = Array();
	while ($row = mysql_fetch_object($result))
	{
		array_push($resp, $row);
	}
	echo json_encode($resp);
}

?>